package com.huluobo.a2204monthparkdemo.parking

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2204monthparkdemo.R
import com.huluobo.a2204monthparkdemo.adapter.ParkingAdapter
import com.huluobo.a2204monthparkdemo.databinding.ActivityParkingBinding
import com.huluobo.base.bean.ParkingBean
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class ParkingActivity : BaseActivity<ActivityParkingBinding, ParkingViewModel>() {
    private lateinit var parkingAdapter: ParkingAdapter
    private var position = 0
    override fun initData() {
        viewModel.getAllParking()

        viewModel.getAllParkingSuccess.observe(this) {
            val list = Gson().fromJson(it, ParkingBean::class.java)
            parkingAdapter.data.clear()
            parkingAdapter.data.addAll(list)
            parkingAdapter.notifyDataSetChanged()
        }
        viewModel.deleteParkingSuccess.observe(this) {
            ToastUtils.showLong("删除成功")
            parkingAdapter.remove(position)
        }
    }

    override fun initView() {
        binding.parkingHeader.headerTitle.text = "车位申请"
        binding.parkingHeader.headerBack.setOnClickListener { finish() }

        binding.parkingRv.layoutManager = LinearLayoutManager(this)
        parkingAdapter = ParkingAdapter()
        binding.parkingRv.adapter = parkingAdapter

        parkingAdapter.setOnItemLongClickListener { adapter, view, position ->
            this.position = position
            val map = mutableMapOf<String, Int>()
            map[Const.PARAM_PARK_ID] = parkingAdapter.data[position].parkId
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            viewModel.deleteParking(body)
            true
        }

        parkingAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(this, ParkingVRActivity::class.java)
            intent.putExtra(Const.URL_PARKING, parkingAdapter.data[position])
            startActivity(intent)
        }
    }
}